<template>
  <div class="social-media-chart-container" ref="chartContainer">
    <div class="switch-wrapper" @click.stop>
      <div class="social-media-info">
        <div class="platform-details">
          <div class="platform-title">Review overview by sources</div>
          <div class="platform-review-count">
            {{ totalReviewCount.toLocaleString() }}
          </div>
          <div class="platform-review-label">Reviews</div>
        </div>
        <div class="platform-switch">
          <div class="switch-label">Social media</div>
          <div>
            <el-switch
              v-model="mediaSwitch"
              active-color="#4CAF50"
              inactive-color="#f44336"
              @change="handleSwitchChange"
            ></el-switch>
            <span class="switch-text" :class="{ 'is-active': mediaSwitch }">
              {{ mediaSwitch ? "on" : "off" }}
            </span>
          </div>
        </div>
      </div>
      <div class="chart-container" style="pointer-events: none">
        <PieChart
          ref="pieChart"
          :option="localChartOption"
          :height="chartHeight"
          :width="chartWidth"
        ></PieChart>
      </div>
    </div>
  </div>
</template>

<script>
import { fontChart } from "@/utils/echartPxToRem";
import PieChart from "@components/common/PieChart.vue";

export default {
  components: { PieChart },
  data() {
    return {
      chartWidth: "4.1667rem",
      chartHeight: "1.4375rem",
      mediaSwitch: true,
      currentChartData: null,
      chartInstance: null,
      localChartOption: this.createChartOption(),
      resizeObserver: null,
      screenWidth: window.innerWidth,
    };
  },
  computed: {
    totalReviewCount() {
      const activeData = this.mediaSwitch
        ? this.calculatedChartData.allSources
        : this.calculatedChartData.socialMedia;
      return activeData.reduce((sum, item) => sum + item.value, 0);
    },
    calculatedChartData() {
      const infoPlatformsTotal = this.ratingInfos
        .filter((item) => ["Tripadvisor", "Google"].includes(item.platform))
        .reduce((sum, item) => sum + item.reviews, 0);

      const otasTotal = this.ratingInfos
        .filter((item) =>
          ["Booking", "Expedia", "Trip"].includes(item.platform)
        )
        .reduce((sum, item) => sum + item.reviews, 0);

      return {
        socialMedia: [
          {
            value: 2000,
            name: "Direct booking",
            itemStyle: { color: "#B0BEC5" }, // 扇形图颜色
          },
          {
            value: infoPlatformsTotal,
            name: "Information Platforms",
            itemStyle: { color: "#2FAA68" }, // 扇形图颜色
          },
          { value: otasTotal, name: "OTAs", itemStyle: { color: "#5D8FDC" } }, // 扇形图颜色
        ],
        allSources: [
          {
            value: 1091,
            name: "Social Media",
            itemStyle: { color: "#B38DCB" }, // 扇形图颜色
          },
          {
            value: 2000,
            name: "Direct booking",
            itemStyle: { color: "#B0BEC5" },
          },
          {
            value: infoPlatformsTotal,
            name: "Information Platforms",
            itemStyle: { color: "#2FAA68" },
          },
          { value: otasTotal, name: "OTAs", itemStyle: { color: "#5D8FDC" } },
        ],
      };
    },
    activeChartData() {
      return this.mediaSwitch
        ? this.calculatedChartData.allSources
        : this.calculatedChartData.socialMedia;
    },
    ratingInfos() {
      return this.$store.state.dashBoard.ratingInfos;
    },
  },
  methods: {
    createChartOption() {
      return {
        tooltip: { trigger: "item" },
        legend: {
          orient: "vertical",
          left: "0%",
          bottom: "0%",
          itemWidth: 20, // 图例圆形图标宽度（与扇形图颜色一致）
          itemHeight: 20, // 图例圆形图标高度
          itemGap: 2,
          borderWidth: 0,
          padding: [10, 0, 0, 24],
          filter: (item) => {
            const dataItem = this.localChartOption.series[0].data.find(
              (data) => data.name === item.name
            );
            return dataItem && dataItem.value > 0;
          },
          formatter: (name) => {
            const item = this.localChartOption.series[0].data.find(
              (dataItem) => dataItem.name === name
            );
            return `${name}  {valueStyle|${item.value.toLocaleString()}}`;
          },
          textStyle: {
            color: "#454545", // 图例文本颜色（原始配置，固定为#454545）
            fontSize: 12,
            rich: {
              valueStyle: {
                fontWeight: "bold",
                fontSize: 12,
                color: "#454545", // 数值文本颜色也保持#454545
              },
            },
            padding: [0, 0, 0, 4],
          },
          data: [
            {
              name: "Direct booking",
              icon: "circle", // 圆形图标
              // 图例文本颜色继承上面的textStyle.color（#454545），不单独设置
            },
            {
              name: "Information Platforms",
              icon: "circle",
            },
            { name: "OTAs", icon: "circle" },
            {
              name: "Social Media",
              icon: "circle",
            },
          ],
        },
        series: [
          {
            name: "Access From",
            type: "pie",
            borderColor: "#fff",
            radius: ["26%", "90%"],
            center: ["80%", "50%"],
            grid: { top: 0, left: 0, right: 0, bottom: 0 },
            avoidLabelOverlap: false,
            itemStyle: { borderWidth: 2, borderColor: "#fff" },
            label: {
              show: true,
              position: "inside",
              color: "#fff",
              formatter: function (params) {
                const percent = params.percent;
                return `{percentStyle|${percent}%}`;
              },
              align: "center",
              bleedMargin: 0,
              padding: [0, 0],
              rich: {
                percentStyle: {
                  padding: [1, 2],
                  width: 25,
                  height: 25,
                  align: "center",
                  verticalAlign: "middle",
                  fontSize: 11,
                  color: "#fff",
                },
              },
            },
            emphasis: {
              scale: false,
              label: {
                show: true,
                position: "inside",
                color: "#fff",
                formatter: params => `\n{percentStyle|${params.percent}%}`,
                align: "center",
                bleedMargin: 0,
                padding: [0, 0],
                rich: {
                  percentStyle: {
                    padding: [1, 2],
                    width: 25,
                    height: 25,
                    align: "center",
                    verticalAlign: "middle",
                    fontSize: 10,
                    color: "#fff",
                  },
                },
              },
              labelLine: { show: false },
              itemStyle: { borderWidth: 2, borderColor: "#fff" },
            },
            labelLine: { show: false },
          },
        ],
      };
    },

    handleSwitchChange(value) {
      this.$store.commit("dashBoard/updateSwitchState", value);
      this.$nextTick(() => {
        this.mediaSwitch = value;
        this.updateChartData(value);
        this.resizeChart();
      });
    },

    updateChartData(isSocialMedia) {
      const newData = isSocialMedia
        ? this.calculatedChartData.allSources
        : this.calculatedChartData.socialMedia;

      const isSmallScreen = this.screenWidth <= 1150;
      const labelFontSize = isSmallScreen ? 9 : 11;

      // 核心：图例文本颜色保持#454545，图例圆形图标颜色与扇形图一致（ECharts自动关联series.data的颜色）
      this.localChartOption = {
        ...this.createChartOption(),
        legend: {
          ...this.createChartOption().legend,
          show: !isSmallScreen, // 仅控制显示/隐藏
          data: newData.map(item => ({ name: item.name, icon: "circle" })), // 不设置textStyle.color，继承#454545
        },
        series: [
          {
            ...this.createChartOption().series[0],
            data: newData, // 扇形图颜色在这里定义，图例圆形图标会自动同步此颜色
            label: {
              ...this.createChartOption().series[0].label,
              rich: {
                ...this.createChartOption().series[0].label.rich,
                percentStyle: {
                  ...this.createChartOption().series[0].label.rich.percentStyle,
                  fontSize: labelFontSize, // 仅改label字体大小
                },
              },
            },
          },
        ],
      };
    },

    calculateChartSize() {
      if (this.$refs.chartContainer) {
        this.chartWidth = `${Math.max(this.$refs.chartContainer.offsetWidth - 24, 300)}px`;
      }
    },

    resizeChart() {
      if (this.$refs.pieChart?.chartInstance) {
        this.$refs.pieChart.chartInstance.resize();
      }
    },
  },
  mounted() {
    this.calculateChartSize();
    this.resizeObserver = new ResizeObserver(() => {
      this.calculateChartSize();
      this.resizeChart();
    });
    if (this.$refs.chartContainer) {
      this.resizeObserver.observe(this.$refs.chartContainer);
    }

    window.addEventListener("resize", () => {
      this.screenWidth = window.innerWidth;
      this.updateChartData(this.mediaSwitch);
    });

    this.updateChartData(this.mediaSwitch);
  },
  beforeDestroy() {
    window.removeEventListener("resize", () => {
      this.screenWidth = window.innerWidth;
      this.updateChartData(this.mediaSwitch);
    });
    window.removeEventListener("resize", this.calculateChartSize);
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
  },
  watch: {
    activeChartData: { handler() { this.updateChartData(this.mediaSwitch); }, deep: true },
    ratingInfos: { handler() { this.updateChartData(this.mediaSwitch); }, immediate: true, deep: true },
  },
};
</script>

<style lang="scss" scoped>
.social-media-chart-container {
  position: relative;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  height: 1.9583rem;
  border-radius: 0.0556rem;
  border: 1px solid #cdcccc;
  background: #fff;

  .social-media-info {
    margin: 24px 45px 32px 24px;
    min-height: 120px;

    .platform-details {
      margin-bottom: 0.0903rem;

      .platform-title {
        font-size: 0.1389rem;
        font-weight: 600;
        margin-bottom: 16px;
        color: #454545;
      }

      .platform-review-count {
        font-size: 0.1667rem;
        font-weight: 700;
        color: #232323;
        margin-bottom: 3px;
      }

      .platform-review-label {
        font-size: 0.0694rem;
        font-weight: 400;
        color: #454545;
      }
    }

    .platform-switch {
      display: flex;
      justify-content: space-between;

      .switch-label {
        font-size: 0.0972rem;
        font-weight: 600;
        color: #6a6969;
      }
    }
  }

  .chart-container {
    position: absolute;
    right: 0;
    top: 0.1042rem;
    margin: 37px 24px;
  }
}
</style>
<style lang="scss">
::v-deep .el-switch {
  .el-switch__label {
    font-size: 0.1111rem !important;
    color: #454545;
    padding: 0 5px;
  }
}
.switch-with-text {
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch-text {
  color: #f44336;

  &.is-active {
    color: #4caf50;
  }
}

::v-deep .el-switch {
  margin: 0;
}
</style>